// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()
const _ = db.command
// 云函数入口函数
// 用于升级桶押金的支付/退款
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  return upgradeBarrelInfo2BarrelPay();
  // return confirmAllUpgraded()

}

const confirmAllUpgraded = async () => {
  const userRes = await db.collection('users').where({
    barrelInfo: _.exists(true),
    barrelPay: _.exists(false)
  }).get()

  return userRes
}

const upgradeBarrelInfo2BarrelPay = async () => {
  const userRes = await db.collection('users').where({
    barrelInfo: _.exists(true)
  }).get()
  const users = userRes.data
  const resArray = []
  for (const user of users) {
    const barrelInfo = user.barrelInfo
    const res = await db.collection('users').where({
        _id: user._id
      })
      .update({
        data: {
          barrelPay: {
            barrel: barrelInfo.barrel,
            payList: [{ // 已经不使用，用 barrelPay.list 替代
              outTradeNo: barrelInfo.outTradeNo,
              payStatus: barrelInfo.payStatus,
              pladge: barrelInfo.pladge,
              refound: barrelInfo.refound,
              timeCreate: barrelInfo.updateTime,
              timeEnd: parseInt(barrelInfo.timeEnd || 0),
              transactionId: barrelInfo.transactionId
            }]
          }
        }
      })
    resArray.push(res)
  }

  return resArray
}